package com.fdb.efp.nls.service.impl;

import com.fdb.basic.framework.core.base.FrameworkService;
import com.fdb.basic.framework.core.util.DateTool;
import com.fdb.basic.framework.core.util.StringUtil;
import com.fdb.efp.nls.common.constant.BdSzdConstant;
import com.fdb.efp.nls.service.facade.OnlineVerificationBatchService;
import com.fdb.efp.cus.service.facade.CusIndivExtService;
import com.fdb.efp.cus.service.vo.CusIndivExtVO;
import com.fdb.efp.esb.service.bo.req.dxmszd.OnlineVerificationReq;
import com.fdb.efp.esb.service.bo.resp.dxmszd.OnlineVerificationResp;
import com.fdb.efp.esb.service.facade.dxmszd.OnlineVerificationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 联网核查批次任务
 *
 * @author liangcongming :2020/5/8 16:08
 * @version 0.1
 * @date 2020/5/8 16:08
 * @since 2020/5/8 16:08
 */
@Service("onlineVerificationBatchService")
public class OnlineVerificationBatchServiceImpl implements OnlineVerificationBatchService, FrameworkService {

    @Value("${onlineVerification.perSize}")
    private int perSize;//每次处理量

    @Autowired
    @Qualifier("onlineVerificationService")
    private OnlineVerificationService onlineVerificationService;

    @Autowired
    @Qualifier("cusIndivExtService")
    private CusIndivExtService cusIndivExtService;// 客户信息拓展表

    private final static Logger log = LoggerFactory.getLogger(OnlineVerificationBatchServiceImpl.class);

    private static final String LOGGER_ID = "省再担联网核查批次";

    @Override
    public boolean batchCallOnlineCheck() {
        // 1.判断当前时间是否在7点-19点
        int hour = DateTool.getHour(new Date());
        if (hour < 7 || hour >= 19) {
            log.info(LOGGER_ID + ":联网核查批次不在规定时间段内执行，批次结束");
            return true;
        }

        // 2.抽个人客户信息拓展表中未进行过联网核查的客户
        CusIndivExtVO cusIndivExtVO = new CusIndivExtVO();
        cusIndivExtVO.setOnlineVerfStatus(BdSzdConstant.OnlineVerfStatus.NONE);
        // 可配置
        cusIndivExtVO.setPage(1);//固定1，只查第一页
        cusIndivExtVO.setSize(perSize > 0 ? perSize : 100);
        List<CusIndivExtVO> needToCheckVos = cusIndivExtService.queryCusByStatusByPage(cusIndivExtVO);

        if (needToCheckVos == null || needToCheckVos.isEmpty()) {
            log.info(LOGGER_ID + ":没有抽到需要进行联网核查的数据，批次结束！");
            return true;
        }

        log.info(LOGGER_ID + ":抽到需要进行联网核查的数据:" + needToCheckVos.size() + "条！");

        // 3.拼凑请求,调联网核查接口，并更新联网核查状态
        for (CusIndivExtVO vo : needToCheckVos) {
            try {
                OnlineVerificationReq req = new OnlineVerificationReq();
                req.setTxnCd("CG1041");//交易码（公共信息）
                req.setAcctNm(vo.getCusName());
                req.setCertNo(vo.getCertCode());
                OnlineVerificationResp resp = onlineVerificationService.callOnlineCheck(req);

                CusIndivExtVO checkedVo = new CusIndivExtVO();
                checkedVo.setCusId(vo.getCusId());
                checkedVo.setLastUpdateTime(DateTool.getCurrentDateTime());
                checkedVo.setLastUpdateUser("onlineVerificationBatchService");

                if (resp == null) { // 调用接口异常
                    log.error(LOGGER_ID + "联网核查消费接口调用失败！本次任务结束，待下次轮训重试" );
                } else if (resp != null && "000000".equals(resp.getResult())) { // 核查成功
                    checkedVo.setOnlineVerfStatus(BdSzdConstant.OnlineVerfStatus.DONE);
                    checkedVo.setRetCode(resp.getExmnRslt());// 联网核查系统响应结果
                } else { //核查失败
                    checkedVo.setOnlineVerfStatus(BdSzdConstant.OnlineVerfStatus.ERROR);
                    String result = resp.getExmnRslt();
                    if(StringUtil.isNotEmpty(resp.getExmnRslt()) && resp.getExmnRslt().length() > 100 ){
                        result = resp.getExmnRslt().substring(0,100);
                    }
                    checkedVo.setRetCode(result);//ESB响应结果
                }

                int num = cusIndivExtService.updateByPk(checkedVo);

                if (num == -1) {
                    log.error(LOGGER_ID + ":个人客户信息拓展表数据库状态更新失败！CusId：" + vo.getCusId());
                } else {
                    log.info(LOGGER_ID + ":个人客户信息拓展表数据库状态更新成功！CusId：" + vo.getCusId());
                }
            } catch (Exception e) {
                log.error(LOGGER_ID + ":联网核查消费接口批次调用失败！" + e.getMessage(),e);
            }
        }
        return true;
    }


}
